import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw'

import { User } from './user';

@Injectable()
export class UserService {
  private userUrl = 'http://localhost:8080';

  constructor(private http: Http) { }

  //获取用户列表
  public getUsers(): Observable<User[]> {
    return this.http.get(this.userUrl + "/list")
      .map(this.extractData)
      .catch(this.handleError);
  }



  //添加,修改用户
  public addUser(user: User): Observable<string> {
    let params = new URLSearchParams();
    params.set('userInfo', JSON.stringify(user));

    return this.http.post(this.userUrl + "/addUser", params)
      .map(this.extractData)
      .catch(this.handleError);
  }

  //删除用户
  public delUser(id: number): Observable<string> {
    return this.http.get(this.userUrl + "/delUser/" + id)
      .map(this.extractData)
      .catch(this.handleError);
  }

  //获取一个用户
  public getOneUser(id: number): Observable<User> {
    return this.http.get(this.userUrl + "/getOneUser/" + id)
      .map(this.extractData)
      .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  private handleError(error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error("err" + errMsg);
    return Observable.throw(errMsg);
  }
}
